package com.dorm.service;

import com.dorm.entity.Room;
import com.dorm.entity.Student;
import com.dorm.mapper.RoomMapper;
import com.dorm.mapper.StudentMapper;
import com.dorm.util.Debug;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class RoomService {
    private final RoomMapper roomMapper;
    private final StudentMapper studentMapper;

    public RoomService(RoomMapper roomMapper, StudentMapper studentMapper) {
        this.roomMapper = roomMapper;
        this.studentMapper = studentMapper;
    }

    public List<Room> getAllRooms() {
        return roomMapper.findAll();
    }

    public Room getRoomById(Long id) {
        return roomMapper.findById(id);
    }

    public List<Room> getRoomsByBuilding(Long buildingId) {
        return roomMapper.findByBuildingId(buildingId);
    }

    public Room createRoom(Room room) {
        roomMapper.insert(room);
        return room;
    }

    public Room updateRoom(Room room) {
        roomMapper.update(room);
        return room;
    }

    @Transactional
    public void deleteRoom(Long id) {
        try {
            // 检查房间是否存在
            Room room = roomMapper.findById(id);
            if (room == null) {
                throw new RuntimeException("房间不存在");
            }

            // 检查房间是否有学生
            List<Student> students = studentMapper.findByRoomId(id);
            if (students != null && !students.isEmpty()) {
                throw new RuntimeException("房间内还有学生，无法删除");
            }

            // 删除房间相关的卫生检查记录
            roomMapper.deleteHygieneRecords(id);

            // 删除房间
            int result = roomMapper.deleteById(id);
            if (result <= 0) {
                throw new RuntimeException("删除房间失败");
            }
        } catch (Exception e) {
            Debug.error("删除房间失败:", e);
            throw new RuntimeException("删除房间失败: " + e.getMessage());
        }
    }

    public Room getRoomWithStudents(Long id) {
        return roomMapper.findRoomWithStudents(id);
    }
} 